package com.xunshangwang.pinhaohuo.transformation;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.support.v4.content.ContextCompat;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

/**
 * Created by xzp on 15/12/22.
 */
public class CircleTransformation extends BitmapTransformation {
    private int mBorderSize;
    private int mBorderColor;
    public CircleTransformation(Context context) {
        this(context, -1, -1);
    }
    public CircleTransformation(Context context,int borderResId,int colorResId){
        super(context);
        if(borderResId>0){
            mBorderSize=context.getResources().getDimensionPixelOffset(borderResId);
        }
        if(colorResId>0){
            mBorderColor= ContextCompat.getColor(context,colorResId);
        }else {
            mBorderColor=Color.WHITE;
        }
    }
    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        Bitmap bitmap=pool.get(outWidth,outHeight, Bitmap.Config.ARGB_8888);
        if(bitmap==null){
            bitmap=Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
        }
        Canvas canvas=new Canvas(bitmap);
        if(mBorderSize>0){
            Paint paint=new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(mBorderColor);
            canvas.drawCircle(outWidth/2,outHeight/2,outWidth/2,paint);
        }
        BitmapShader shader = new BitmapShader(toTransform, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        float scale = Math.min((outWidth-mBorderSize) * 1.0f / toTransform.getWidth(), (outHeight-mBorderSize)
                * 1.0f / toTransform.getHeight());
        Matrix matrix= new Matrix();
        if(scale<0)
            scale=1;
        matrix.setScale(scale,scale);
        shader.setLocalMatrix(matrix);
        Paint bitmapPaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        bitmapPaint.setShader(shader);
        canvas.drawCircle(outWidth/2,outHeight/2,outWidth/2-mBorderSize,bitmapPaint);
        return bitmap;
    }

    @Override
    public String getId() {
        return "com.xunshangwang.pinhaohuo.transformation.CircleTransformation";
    }
}
